import React, { useCallback, useEffect, useState } from 'react'
import { View, Image } from '@tarojs/components'
import classNames from 'classnames'
import './nav.scss'
import { useSelector, useDispatch } from 'react-redux'
import { setGlobal } from '../../redux/actions/counter'
import { navigateBack } from '@tarojs/taro'


const getGlobal = () => {
  const globalData = useSelector(state => state.globalData)
  if (globalData.navTop && globalData.menuButtonHeight) {
    console.log(globalData, 'globalData')
    return
  }
  const dispatch = useDispatch()
  let menuButtonObject = wx.getMenuButtonBoundingClientRect();
  wx.getSystemInfo({
    success: res => {
      let statusBarHeight = res.statusBarHeight,
        navTop = menuButtonObject.top,//胶囊按钮与顶部的距离
        navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;//导航高度
      dispatch(setGlobal({
        navHeight,
        navTop,
        menuButtonHeight: menuButtonObject.height
      }))
    },
    fail(err) {
      console.log(err);
    }
  })
}

const Navbar = ({ titleText = '', isFixed = false, titleAlign = 'left', isSwitchPage = false, isShowBorder = true, backColor = '#fff' }) => {

  getGlobal()

  const globalData = useSelector(state => state.globalData)

  let styleStr = {
    height: globalData.menuButtonHeight + 2 + 'px',
    paddingTop: globalData.navTop + 'px',
  }

  const [isFirstPage, setIsFirstPage] = useState(false)
  styleStr = Object.assign(styleStr, {
    borderBottom: `2px solid ${isShowBorder ? `rgba(250, 250, 250, 1)` : `none`};`,
    backgroundColor: backColor
  })

  return <View className={classNames('navbar-container', isFixed ? 'navbar-fixed' : '')} style={styleStr}>
    {!isSwitchPage ?
      <View className="left-item">
        <Image className="icon-index" onClick={navigateBack} src={isFirstPage ? null : 'https://glack.net/img/profile/1603702065930.png'} mode="widthFix" />
      </View>
      : null}
    {titleText ? <View className="center-item" style={{ textAlign: titleAlign }}>{titleText}</View> : null}
  </View>
}

export default Navbar